package com.yn.service.zy.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yn.common.enums.BooleanEnum;
import com.yn.common.exception.TransitException;
import com.yn.common.model.article.ArticleTitleManage;
import com.yn.common.model.zy.TDoctorInfoDO;
import com.yn.common.model.zy.TOrganInfoDO;
import com.yn.common.page.BasePage;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.request.zy.OrganInfoAddRequest;
import com.yn.common.response.zy.OrganQueryResponse;
import com.yn.common.utils.PhoneValidator;
import com.yn.service.dao.zy.TDoctorInfoMapper;
import com.yn.service.dao.zy.TOrganInfoMapper;
import com.yn.service.service.SystemAttachmentService;
import com.yn.service.service.SystemConfigService;
import com.yn.service.zy.TOrganInfoService;
import com.yn.service.zy.model.dto.TOrganInfoDTO;
import com.yn.service.zy.model.query.TOrganInfoQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


@Service
@Slf4j
public class TOrganInfoServiceImpl extends ServiceImpl<TOrganInfoMapper, TOrganInfoDO> implements TOrganInfoService {

    @Resource
    private TOrganInfoMapper tOrganInfoMapper;

    @Resource
    private TDoctorInfoMapper doctorInfoMapper;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private SystemAttachmentService systemAttachmentService;

    /**
     * 分页查询机构信息列表
     * @param query 机构信息查询对象
     * @param pageParamRequest 分页参数
     * @return 机构信息列表
     */
    @Override
    public PageInfo<OrganQueryResponse> listPage(TOrganInfoQuery query, PageParamRequest pageParamRequest) {
        Page<TOrganInfoDO> organPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<TOrganInfoDO> queryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotEmpty(query.getAreaCode())){
            queryWrapper.eq(TOrganInfoDO::getRegionCode,query.getAreaCode());
        }

        if(StringUtils.isNotEmpty(query.getOrganFeature())){
            queryWrapper.eq(TOrganInfoDO::getOrganFeature,query.getOrganFeature());
        }
        if(StringUtils.isNotEmpty(query.getOrganType())){
            queryWrapper.eq(TOrganInfoDO::getOrganType,query.getOrganType());
        }
        if(StringUtils.isNotEmpty(query.getOrganName())){
            queryWrapper.like(TOrganInfoDO::getOrganName,query.getOrganName());
        }
        if(StringUtils.isNotEmpty(query.getDevice())){
            queryWrapper.like(TOrganInfoDO::getDeviceInfo,query.getDevice());
        }
        if(!ObjectUtils.isEmpty(query.getPrice())){
            queryWrapper.eq(TOrganInfoDO::getPrice,query.getPrice());
        }

        queryWrapper.eq(TOrganInfoDO::getIsDelTag, BooleanEnum.NO.getCode());
        queryWrapper.orderByDesc(TOrganInfoDO::getCreateTime);

        List<TOrganInfoDO> organList = baseMapper.selectList(queryWrapper);
        ArrayList<OrganQueryResponse> organDTOList = new ArrayList<>();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(organList)) {
            return BasePage.copyPageInfo(organPage, organDTOList);
        }
        for (TOrganInfoDO infoDO : organList) {
            OrganQueryResponse transform = OrganQueryResponse.transform(infoDO);
            if (ObjectUtils.isEmpty(transform)) {
                continue;
            }
            //这个Map里的key是存入字典表里的value，集合的value是字典表里的title
            Map<String, String> mapByName = systemConfigService.getMapByName("organ_charging_unit");
            if(CollUtil.isEmpty(mapByName)){
                transform.setUnitStr("");
            }else{
                transform.setUnitStr(mapByName.get(transform.getUnit()));
            }
            organDTOList.add(transform);
        }
        return BasePage.copyPageInfo(organPage, organDTOList);
    }

    /**
     * 获取机构详情
     * @param id
     * @return
     */
    @Override
    public TOrganInfoDTO getInfo(Integer id) {
        TOrganInfoDO tOrganInfoDO = tOrganInfoMapper.selectById(id);
        if(tOrganInfoDO== null){
           return null;
        }
        //根据单位的value查key
        TOrganInfoDTO transform = TOrganInfoDTO.transform(tOrganInfoDO);
        if (ObjectUtils.isEmpty(transform)) {
            return null;
        }
        //这个Map里的key是存入字典表里的value，集合的value是字典表里的title
        Map<String, String> mapByName = systemConfigService.getMapByName("organ_charging_unit");
        if(CollUtil.isEmpty(mapByName)){
            transform.setUnitStr("");
        }else{
            transform.setUnitStr(mapByName.get(transform.getUnit()));
        }

        return transform;
    }

    /**
     * 新增机构信息
     * @param request 机构信息新增对象
     * @return
     */
    @Override
    @Transactional
    public void saveOrganInfo(OrganInfoAddRequest request) {
        boolean valid = PhoneValidator.isValid(request.getTelPhone());
        if(!valid){
            throw new TransitException("手机号格式错误");
        }
        //根据图片url判断数据库是否存在该图片
        boolean isExist = systemAttachmentService.selectByUrl(request.getOrganImageUrl());
        if(!isExist){
            throw new TransitException("上传图片出现错误");
        }
        //根据机构名称，机构类型查询db
        TOrganInfoDO one = lambdaQuery().eq(TOrganInfoDO::getOrganName, request.getOrganName())
                .eq(TOrganInfoDO::getOrganType, request.getOrganType())
                .eq(TOrganInfoDO::getIsDelTag, 0)
                .one();
        if(one != null) {
            throw new TransitException("机构信息已存在");
        }
        TOrganInfoDO transform = OrganInfoAddRequest.transform(request);

        save(transform);
    }

    /**
     * 修改机构信息
     * @param request 机构信息修改对象
     * @return
     */
    @Override
    @Transactional
    public void modifyOrganInfo(OrganInfoAddRequest request) {
        if(request.getId() == null){
            throw new TransitException("机构信息ID不能为空");
        }
        boolean valid = PhoneValidator.isValid(request.getTelPhone());
        if(!valid){
            throw new TransitException("手机号格式错误");
        }
        //根据图片url判断数据库是否存在该图片
        boolean isExist = systemAttachmentService.selectByUrl(request.getOrganImageUrl());
        if(!isExist){
            throw new TransitException("上传图片出现错误");
        }
        TOrganInfoDO transform = OrganInfoAddRequest.transform(request);
        updateById(transform);
    }

    /**
     * 删除机构信息
     * @param id 机构信息id
     * @return
     */
    @Override
    public void deleteOrganInfo(Integer id) {
        // 判断当前机构下是否有医生信息
        LambdaQueryWrapper<TDoctorInfoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TDoctorInfoDO::getOrganInfoId, id);
        Integer count = doctorInfoMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new TransitException("当前机构下有医生信息，请先删除医生信息");
        }
        removeById(id);
    }
}
